<template>
  <view class="mine-container">
    <!-- 顶部导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @click="goBack">
        <uni-icons type="left" size="20" color="#333"></uni-icons>
      </view>
      <view class="nav-title">
        <text>我的</text>
      </view>
      <view class="nav-right" @click="refreshProfile">
        <uni-icons type="reload" size="20" color="#333"></uni-icons>
      </view>
    </view>

    <!-- 用户信息区域 -->
    <view class="user-info">
      <view class="user-avatar" @click="goToProfileOrLogin">
        <image :key="userInfo.avatar" :src="userInfo.avatar" mode="aspectFill" @error="onAvatarError"></image>
      </view>
      <view class="user-details" @click="goToProfileOrLogin">
        <text class="username">{{ userInfo.nickname || '未登录' }}</text>
        <text class="user-desc">{{ userInfo.signature || '点击登录/注册' }}</text>
      </view>
      <view class="user-action" @click="goToProfileOrLogin">
        <uni-icons type="right" size="16" color="#999"></uni-icons>
      </view>
    </view>

    <!-- 功能菜单 -->
    <view class="menu-section">
      <!-- 我的档案 -->
      <view class="menu-item" @click="tipMedicalRecord">
        <view class="menu-icon">
          <uni-icons type="person" size="20" color="#007AFF"></uni-icons>
        </view>
        <text class="menu-title menu-title--disabled">我的档案（待开发）</text>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 我的关注 -->
      <view class="menu-item" @click="goToFollowing">
        <view class="menu-icon">
          <uni-icons type="heart" size="20" color="#FF6B6B"></uni-icons>
        </view>
        <text class="menu-title">我的关注</text>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 我的收藏 -->
      <view class="menu-item" @click="goToFavorites">
        <view class="menu-icon">
          <uni-icons type="star" size="20" color="#FFD93D"></uni-icons>
        </view>
        <text class="menu-title">我的收藏</text>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 我的消息 -->
      <view class="menu-item" @click="goToMessages">
        <view class="menu-icon">
          <uni-icons type="chat" size="20" color="#4ECDC4"></uni-icons>
        </view>
        <text class="menu-title">我的消息</text>
        <view class="menu-badge" v-if="messageCount > 0">
          <text>{{ messageCount > 99 ? '99+' : messageCount }}</text>
        </view>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 我购买的视频 -->
      <view class="menu-item" @click="goToPurchasedVideos">
        <view class="menu-icon">
          <uni-icons type="videocam" size="20" color="#9B59B6"></uni-icons>
        </view>
        <text class="menu-title">我购买的视频</text>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 被采纳建议 -->
      <view class="menu-item" @click="goToAdoptedSuggestions">
        <view class="menu-icon">
          <uni-icons type="checkmarkempty" size="20" color="#2ECC71"></uni-icons>
        </view>
        <text class="menu-title">被采纳建议</text>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 分割线 -->
    <view class="divider"></view>

    <!-- 账户相关 -->
    <view class="menu-section">
      <!-- 我的钱包 -->
      <view class="menu-item" @click="goToWallet">
        <view class="menu-icon">
          <uni-icons type="wallet" size="20" color="#6C5CE7"></uni-icons>
        </view>
        <text class="menu-title">我的钱包</text>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
      <!-- 登录注册 -->
      <view class="menu-item" @click="goToAuth">
        <view class="menu-icon">
          <uni-icons type="contact" size="20" color="#E67E22"></uni-icons>
        </view>
        <text class="menu-title">登录注册</text>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>

      <!-- 设置 -->
      <view class="menu-item" @click="goToSettings">
        <view class="menu-icon">
          <uni-icons type="gear" size="20" color="#95A5A6"></uni-icons>
        </view>
        <text class="menu-title">设置</text>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 分割线 -->
    <view class="divider"></view>

    <!-- 社交功能 -->
    <view class="menu-section">
      <!-- 我的病友圈 -->
      <view class="menu-item" @click="goToMyCommunity">
        <view class="menu-icon">
          <uni-icons type="chatbubble" size="20" color="#3498DB"></uni-icons>
        </view>
        <text class="menu-title">我的病友圈</text>
        <view class="menu-arrow">
          <uni-icons type="right" size="16" color="#999"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 底部功能 -->
    <view class="bottom-section">
      <!-- 发送给好友 -->
      <view class="bottom-item" @click="shareToFriend">
        <uni-icons type="forward" size="16" color="#999"></uni-icons>
        <text>发送给好友</text>
      </view>

      <!-- 二级页-获取H币页 -->
      <view class="bottom-item" @click="goToCoins">
        <uni-icons type="wallet" size="16" color="#999"></uni-icons>
        <text>二级页-获取H币页</text>
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters } from 'vuex'

export default {
  data() {
    return {
      userInfo: {
        avatar: '/static/images/profile.jpg',
        nickname: '',
        signature: ''
      },
      messageCount: 3 // 示例消息数量
    }
  },
  computed: {
    ...mapGetters(['name', 'avatar', 'token'])
  },
  onLoad() {
    this.loadUserInfo()
  },
  onShow() {
    // 每次显示页面时都重新加载用户信息
    this.loadUserInfo()
  },
  // 支持下拉刷新触发手动刷新
  onPullDownRefresh() {
    this.refreshProfile()
  },
  methods: {
    // 手动刷新：清空缓存并重新拉取
    async refreshProfile() {
      try {
        uni.showLoading({ title: '刷新中' })
        // 1) 清理“我的”页私有缓存
        uni.removeStorageSync('profileInfo')
        // 2) 强制刷新全局用户缓存（store 内部将跳过TTL并回写全局缓存）
        const res = await this.$store.dispatch('GetInfo', { forceRefresh: true })
        const d = (res && res.data) ? res.data : {}
        // 3) 回填“我的”页本地轻量缓存，方便本页离线展示
        const profileInfo = {
          avatar: d.avatar || this.avatar || '/static/images/profile.jpg',
          patientName: d.patientName || d.nickName || d.username || d.userName || this.name || '',
          phone: d.phonenumber || d.phone || '',
          sex: (function(v){
            if (v === 0 || v === 1) return v
            if (v === '0' || v === '男' || v === 'M' || v === 'm') return 0
            if (v === '1' || v === '女' || v === 'F' || v === 'f') return 1
            if (v === true) return 1
            if (v === false) return 0
            return v == null ? null : v
          })(d.sex ?? d.gender),
          age: d.age != null ? d.age : '',
          nation: d.nation || d.nationality || '',
          ts: Date.now()
        }
        uni.setStorageSync('profileInfo', profileInfo)
        this.userInfo = {
          avatar: profileInfo.avatar,
          nickname: profileInfo.patientName,
          signature: profileInfo.patientName ? '已登录' : '点击登录/注册'
        }
        uni.setStorageSync('userInfo', this.userInfo)
        // 4) 可选：广播通知其他页面（如需要立即响应）
        uni.$emit && uni.$emit('user-profile-updated', { when: Date.now() })
        uni.showToast({ title: '已刷新', icon: 'none' })
      } catch (e) {
        console.error('手动刷新失败', e)
        uni.showToast({ title: '刷新失败', icon: 'none' })
      } finally {
        uni.hideLoading()
        uni.stopPullDownRefresh && uni.stopPullDownRefresh()
      }
    },
    // 修复返回按钮逻辑
    goBack() {
      // 检查页面栈深度
      const pages = getCurrentPages()
      if (pages.length > 1) {
        // 检查上一页是否是首页或其他主要页面
        const prevPage = pages[pages.length - 2]
        const prevRoute = prevPage.route
        
        // 如果上一页是首页、病友圈、医生列表等主要页面，则返回
        if (prevRoute === 'pages/index' || 
            prevRoute === 'pages/community/index' || 
            prevRoute === 'pages/doctors/index' ||
            prevRoute === 'pages/symptoms/index') {
          uni.navigateBack({
            delta: 1
          })
        } else {
          // 否则跳转到首页
          uni.switchTab({
            url: '/pages/index'
          })
        }
      } else {
        // 如果没有上一页，跳转到首页
        uni.switchTab({
          url: '/pages/index'
        })
      }
    },
    async loadUserInfo() {
      // 检查是否已登录
      if (this.token) {
        try {
          // 1) 先读缓存，存在且未过期(10分钟)则直接使用，避免重复请求
          const EXPIRE_MS = 10 * 60 * 1000
          const cached = uni.getStorageSync('profileInfo')
          if (cached && Object.keys(cached).length) {
            const fresh = cached.ts && (Date.now() - cached.ts) < EXPIRE_MS
            if (fresh) {
              // 用缓存渲染顶部头像/昵称
              this.userInfo = {
                avatar: cached.avatar || '/static/images/profile.jpg',
                nickname: cached.patientName || this.name || '',
                signature: (cached.patientName || this.name) ? '已登录' : '点击登录/注册'
              }
              uni.setStorageSync('userInfo', this.userInfo)
              return
            } else {
              // 超时：清除缓存，进入刷新流程
              uni.removeStorageSync('profileInfo')
            }
          }

          console.log('[Mine] 无本地缓存，首次调用接口 GetInfo')
          const res = await this.$store.dispatch('GetInfo')
          const d = (res && res.data) ? res.data : {}

          // 构造 profileInfo 并写入缓存
          const profileInfo = {
            avatar: d.avatar || this.avatar || '/static/images/profile.jpg',
            patientName: d.patientName || d.nickName || d.username || d.userName || this.name || '',
            phone: d.phonenumber || d.phone || '',
            sex: (function(v){
              // 统一性别到 0(男)/1(女)
              if (v === 0 || v === 1) return v
              if (v === '0' || v === '男' || v === 'M' || v === 'm') return 0
              if (v === '1' || v === '女' || v === 'F' || v === 'f') return 1
              // 兼容可能的布尔/其他类型
              if (v === true) return 1
              if (v === false) return 0
              return v == null ? null : v
            })(d.sex ?? d.gender),
            age: d.age != null ? d.age : '',
            nation: d.nation || d.nationality || '',
            ts: Date.now() // 写入时间戳用于10分钟过期控制
          }
          uni.setStorageSync('profileInfo', profileInfo)

          // 同步一份轻量信息供“我的”页展示
          this.userInfo = {
            avatar: profileInfo.avatar,
            nickname: profileInfo.patientName,
            signature: profileInfo.patientName ? '已登录' : '点击登录/注册'
          }
          uni.setStorageSync('userInfo', this.userInfo)
        } catch (error) {
          console.error('获取用户信息失败:', error)
          // 清除可能过期的token
          this.$store.dispatch('LogOut')
          this.userInfo = {
            avatar: '/static/images/profile.jpg',
            nickname: '',
            signature: '点击登录/注册'
          }
        }
      } else {
        // 未登录状态
        this.userInfo = {
          avatar: '/static/images/profile.jpg',
          nickname: '',
          signature: '点击登录/注册'
        }
        // 清空本地 profileInfo，避免展示旧数据
        uni.removeStorageSync('profileInfo')
      }
    },
    // 头像加载失败兜底到默认头像
    onAvatarError() {
      this.userInfo.avatar = '/static/images/profile.jpg'
    },
    goToLogin() {
      if (!this.userInfo.nickname) {
        uni.navigateTo({ url: '/pages/login' })
      }
    },
    // 新增：根据登录状态跳转到个人信息或登录
    goToProfileOrLogin() {
      if (!this.token || !this.userInfo.nickname) {
        uni.navigateTo({ url: '/pages/login' })
      } else {
        uni.navigateTo({ url: '/pages/profile/index' })
      }
    },
    // 我的档案入口（尚未开发，给出提示）
    tipMedicalRecord() {
      this.$modal.msg('我的病例详情页面尚未开发')
    },
    goToFollowing() {
      if (!this.token) {
        return uni.navigateTo({ url: '/pages/login' })
      }
      uni.navigateTo({ url: '/pages/follow/index' })
    },
    goToFavorites() {
      uni.navigateTo({
        url: '/pages/favorites/index'
      })
    },
    goToMessages() {
      this.$modal.msg('我的消息功能开发中')
    },
    goToPurchasedVideos() {
      this.$modal.msg('我的购买视频功能开发中')
    },
    goToAdoptedSuggestions() {
      this.$modal.msg('被采纳建议功能开发中')
    },
    goToAuth() {
      uni.navigateTo({
        url: '/pages/login'
      })
    },
    goToSettings() {
      uni.navigateTo({ url: '/pages/settings/index' })
    },
    goToWallet() {
      if (!this.token) {
        return uni.navigateTo({ url: '/pages/login' })
      }
      uni.navigateTo({ url: '/pages/wallet/recharge' })
    },
    // 添加缺失的方法
    goToMyCommunity() {
      uni.switchTab({
        url: '/pages/community/index'
      })
    },
    showInfo(title) {
      this.$modal.msg(title)
    },
    shareToFriend() {
      this.$modal.msg('分享功能开发中')
    },
    goToCoins() {
      this.$modal.msg('获取H币页功能开发中')
    }
  }
}
</script>

<style lang="scss" scoped>
.mine-container {
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 添加导航栏样式 */
.nav-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1rpx solid #f0f0f0;
  
  .nav-left {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .nav-title {
    flex: 1;
    text-align: center;
    
    text {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
    }
  }
  
  .nav-right {
    width: 60rpx;
    height: 60rpx;
  }
}

.user-info {
  display: flex;
  align-items: center;
  padding: 40rpx 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
  
  .user-avatar {
    width: 120rpx;
    height: 120rpx;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 30rpx;
    
    image {
      width: 100%;
      height: 100%;
    }
  }
  
  .user-details {
    flex: 1;
    
    .username {
      display: block;
      font-size: 36rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 10rpx;
    }
    
    .user-desc {
      font-size: 26rpx;
      color: #999;
    }
  }
  
  .user-action {
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.menu-section {
  background-color: #fff;
  margin-bottom: 20rpx;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  
  &:last-child {
    border-bottom: none;
  }
  
  .menu-icon {
    width: 60rpx;
    height: 60rpx;
    background-color: #f8f8f8;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 20rpx;
  }
  
  .menu-title {
    flex: 1;
    font-size: 30rpx;
    color: #333;
  }
  
  .menu-badge {
    background-color: #ff4757;
    color: #fff;
    font-size: 20rpx;
    padding: 4rpx 8rpx;
    border-radius: 10rpx;
    margin-right: 10rpx;
    min-width: 32rpx;
    text-align: center;
    
    text {
      line-height: 1;
    }
  }
  
  .menu-arrow {
    width: 40rpx;
    height: 40rpx;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.divider {
  height: 20rpx;
  background-color: #f5f5f5;
}

.bottom-section {
  background-color: #fff;
  padding: 20rpx 30rpx;
  
  .bottom-item {
    display: flex;
    align-items: center;
    padding: 20rpx 0;
    border-bottom: 1rpx solid #f0f0f0;
    
    &:last-child {
      border-bottom: none;
    }
    
    text {
      margin-left: 15rpx;
      font-size: 28rpx;
      color: #666;
    }
  }
}
</style>